package view.component;

import burp.api.montoya.http.message.requests.HttpRequest;
import burp.api.montoya.http.message.responses.HttpResponse;
import controller.ToolController;
import executor.ToolExecutor;
import executor.dsl.DslVariableReplacer;

import manager.ApiManager;
import manager.ConfigManager;
import model.Config;

import model.HttpToolCommand;
import model.SettingModel;
import util.I18nManager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Clipboard;

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


/**
 * Arsenal工具对话框
 * 显示工具列表、命令预览和执行结果，支持筛选功能
 */
public class ArsenalDialog extends JDialog implements I18nManager.LanguageChangeListener {
    
    private JTable toolTable;
    private DefaultTableModel tableModel;
    private TableRowSorter<DefaultTableModel> tableSorter;
    private JTextField toolNameFilterField;
    private JComboBox<String> categoryFilterCombo;
    private JButton clearFilterButton;
    
    // 修改为选项卡面板
    private JTabbedPane commandTabbedPane;
    private JTextArea originalCommandArea;  // 原始命令（未渲染）
    private JTextArea renderedCommandArea;  // 渲染后的命令
    private JTextArea variablesPreviewArea; // 变量预览
    
    private JTextArea commandResultArea;
    private JButton runButton;  // 统一的运行按钮
    private JButton copyCommandButton; // 复制命令按钮（替换原来的刷新变量按钮）
    private JScrollPane resultScrollPane;
    
    private HttpRequest httpRequest;
    private HttpResponse httpResponse;
    private List<HttpRequest> allSelectedRequests; // 新增：所有选中的HTTP请求
    private List<HttpToolCommand> allToolCommands;
    private List<HttpToolCommand> filteredToolCommands;
    private HttpToolCommand selectedToolCommand;
    
    // DSL变量替换器
    private final DslVariableReplacer dslReplacer = new DslVariableReplacer();

    
    /**
     * 构造函数
     * @param httpRequest HTTP请求对象
     * @param httpResponse HTTP响应对象
     */
    public ArsenalDialog(HttpRequest httpRequest, HttpResponse httpResponse) {
        this.httpRequest = httpRequest;
        this.httpResponse = httpResponse;
        this.allSelectedRequests = new ArrayList<>();
        if (httpRequest != null) {
            this.allSelectedRequests.add(httpRequest);
        }
        this.allToolCommands = loadAllToolCommands();
        this.filteredToolCommands = new ArrayList<>(allToolCommands);

        
        initializeDialog();
        initializeComponents();
        layoutComponents();
        setupEventHandlers();
        loadToolData();
        
        // 注册语言变更监听器
        I18nManager.getInstance().addLanguageChangeListener(this);
    }
    
    /**
     * 构造函数（支持多个HTTP请求）
     * @param httpRequest 主HTTP请求对象
     * @param httpResponse HTTP响应对象
     * @param allSelectedRequests 所有选中的HTTP请求列表
     */
    public ArsenalDialog(HttpRequest httpRequest, HttpResponse httpResponse, List<HttpRequest> allSelectedRequests) {
        this.httpRequest = httpRequest;
        this.httpResponse = httpResponse;
        this.allSelectedRequests = allSelectedRequests != null ? new ArrayList<>(allSelectedRequests) : new ArrayList<>();
        if (this.allSelectedRequests.isEmpty() && httpRequest != null) {
            this.allSelectedRequests.add(httpRequest);
        }
        this.allToolCommands = loadAllToolCommands();
        this.filteredToolCommands = new ArrayList<>(allToolCommands);

        
        initializeDialog();
        initializeComponents();
        layoutComponents();
        setupEventHandlers();
        loadToolData();
        
        // 注册语言变更监听器
        I18nManager.getInstance().addLanguageChangeListener(this);
    }
    
    /**
     * 初始化对话框属性
     */
    private void initializeDialog() {
        I18nManager i18n = I18nManager.getInstance();
        setTitle(i18n.getText("dialog.arsenal.title"));
        setSize(1200, 800);  // 增加宽度以适应新增的列
        // 不在这里设置位置，由调用方决定位置
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setModal(true);
//        setModal(false); // 非模态对话框
        
        // 设置图标
        try {
            setIconImage(new ImageIcon(getClass().getResource("/icon.png")).getImage());
        } catch (Exception e) {
            // 图标加载失败，忽略
        }
    }
    
    /**
     * 重写setVisible方法，确保对话框总是在前面显示
     */
    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            // 延迟执行，避免递归调用
            SwingUtilities.invokeLater(() -> {
                toFront();
                requestFocus();
            });
        }
    }
    
    /**
     * 将对话框置于前台
     */
    public void bringToFront() {
        SwingUtilities.invokeLater(() -> {
            // 多重保障确保窗口在前面
            toFront();
            requestFocus();

            // 确保窗口可见且获得焦点
            if (!isVisible()) {
                super.setVisible(true);  // 使用super避免递归
            }
            toFront();
            requestFocus();
        });
    }
    
    /**
     * 初始化UI组件
     */
    private void initializeComponents() {
        // 创建筛选组件
        initializeFilterComponents();
        
        // 创建工具表格
        I18nManager i18n = I18nManager.getInstance();
        String[] columnNames = {
            i18n.getText("arsenal.dialog.table.column.tool.name"),
            i18n.getText("arsenal.dialog.table.column.command"), 
            i18n.getText("arsenal.dialog.table.column.note"),
            i18n.getText("arsenal.dialog.table.column.work.dir"),
            i18n.getText("arsenal.dialog.table.column.category")
        };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格只读
            }
        };
        
        toolTable = new JTable(tableModel);
        toolTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Font uiFont = UIManager.getFont("Table.font");
        if (uiFont == null) uiFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        toolTable.setFont(uiFont);
        toolTable.getTableHeader().setFont(uiFont.deriveFont(Font.BOLD));
        
        // 设置表格行高
        toolTable.setRowHeight(25);
        
        // 设置列宽
        toolTable.getColumnModel().getColumn(0).setPreferredWidth(120);  // 工具名称
        toolTable.getColumnModel().getColumn(1).setPreferredWidth(300);  // 命令
        toolTable.getColumnModel().getColumn(2).setPreferredWidth(150);  // 备注
        toolTable.getColumnModel().getColumn(3).setPreferredWidth(120);  // 工作目录
        toolTable.getColumnModel().getColumn(4).setPreferredWidth(100);  // 分类
        
        // 创建表格排序器
        tableSorter = new TableRowSorter<>(tableModel);
        toolTable.setRowSorter(tableSorter);
        
        // 创建命令选项卡面板
        initializeCommandTabs();
        
        // 创建运行按钮
        runButton = new JButton(i18n.getText("arsenal.dialog.button.run"));
        Font buttonFont = UIManager.getFont("Button.font");
        if (buttonFont == null) buttonFont = new Font(Font.SANS_SERIF, Font.BOLD, 12);
        runButton.setFont(buttonFont);
        runButton.setBackground(new Color(40, 167, 69));
        runButton.setForeground(Color.WHITE);
        runButton.setEnabled(false);
        runButton.setPreferredSize(new Dimension(100, 30));
        
        // 创建复制命令按钮（替换原来的刷新变量按钮）
        copyCommandButton = new JButton(i18n.getText("arsenal.dialog.button.copy.command"));
        Font copyButtonFont = UIManager.getFont("Button.font");
        if (copyButtonFont == null) copyButtonFont = new Font(Font.SANS_SERIF, Font.BOLD, 11);
        copyCommandButton.setFont(copyButtonFont.deriveFont(11f));
        copyCommandButton.setBackground(new Color(255, 193, 7));
        copyCommandButton.setForeground(Color.BLACK);
        copyCommandButton.setEnabled(false);
        copyCommandButton.setPreferredSize(new Dimension(100, 30));
        
        // 创建执行历史文本框 - 修改为白色背景
        commandResultArea = new JTextArea(8, 50);
        commandResultArea.setEditable(false);
        Font textAreaFont = UIManager.getFont("TextArea.font");
        if (textAreaFont == null) textAreaFont = new Font(Font.SANS_SERIF, Font.PLAIN, 11);
        commandResultArea.setFont(textAreaFont);
        commandResultArea.setBackground(Color.WHITE);  // 修改为白色背景
        commandResultArea.setForeground(Color.BLACK);  // 修改为黑色文字
        commandResultArea.setBorder(BorderFactory.createTitledBorder(i18n.getText("arsenal.dialog.execution.history")));  // 修改标题
        commandResultArea.setText(i18n.getText("arsenal.dialog.execution.hint") + "\n");
        
        resultScrollPane = new JScrollPane(commandResultArea);
        resultScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    }
    
    /**
     * 初始化命令选项卡
     */
    private void initializeCommandTabs() {
        commandTabbedPane = new JTabbedPane();
        Font tabbedPaneFont = UIManager.getFont("TabbedPane.font");
        if (tabbedPaneFont == null) tabbedPaneFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        commandTabbedPane.setFont(tabbedPaneFont);
        
        // 原始命令选项卡
        originalCommandArea = new JTextArea(5, 50);
        originalCommandArea.setEditable(true);  // 可编辑
        originalCommandArea.setFont(new Font("Consolas", Font.PLAIN, 11));
        originalCommandArea.setBackground(new Color(255, 255, 240));  // 浅黄色背景
        originalCommandArea.setLineWrap(true);
        originalCommandArea.setWrapStyleWord(true);
        originalCommandArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JScrollPane originalScrollPane = new JScrollPane(originalCommandArea);
        originalScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        originalScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        // 渲染命令选项卡
        renderedCommandArea = new JTextArea(5, 50);
        renderedCommandArea.setEditable(true);  // 可编辑
        renderedCommandArea.setFont(new Font("Consolas", Font.PLAIN, 11));
        renderedCommandArea.setBackground(new Color(240, 255, 240));  // 浅绿色背景
        renderedCommandArea.setLineWrap(true);
        renderedCommandArea.setWrapStyleWord(true);
        renderedCommandArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JScrollPane renderedScrollPane = new JScrollPane(renderedCommandArea);
        renderedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        renderedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        // 变量预览选项卡
        variablesPreviewArea = new JTextArea(5, 50);
        variablesPreviewArea.setEditable(false);  // 只读
        variablesPreviewArea.setFont(createMonospaceFont());
        variablesPreviewArea.setBackground(new Color(248, 248, 255));  // 浅蓝色背景
        variablesPreviewArea.setLineWrap(true);
        variablesPreviewArea.setWrapStyleWord(true);
        variablesPreviewArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JScrollPane variablesScrollPane = new JScrollPane(variablesPreviewArea);
        variablesScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        variablesScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        // 添加选项卡
        I18nManager tabI18n = I18nManager.getInstance();
        commandTabbedPane.addTab(tabI18n.getText("arsenal.dialog.tab.original.command"), originalScrollPane);
        commandTabbedPane.addTab(tabI18n.getText("arsenal.dialog.tab.rendered.command"), renderedScrollPane);
        commandTabbedPane.addTab(tabI18n.getText("arsenal.dialog.tab.variables.preview"), variablesScrollPane);
        
        // 设置选项卡提示
        commandTabbedPane.setToolTipTextAt(0, tabI18n.getText("arsenal.dialog.tab.tooltip.original"));
        commandTabbedPane.setToolTipTextAt(1, tabI18n.getText("arsenal.dialog.tab.tooltip.rendered"));
        commandTabbedPane.setToolTipTextAt(2, tabI18n.getText("arsenal.dialog.tab.tooltip.variables"));
    }
    
    /**
     * 初始化筛选组件
     */
    private void initializeFilterComponents() {
        // 工具名称筛选框
        I18nManager filterI18n = I18nManager.getInstance();
        toolNameFilterField = new JTextField(15);
        Font filterFieldFont = UIManager.getFont("TextField.font");
        if (filterFieldFont == null) filterFieldFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        toolNameFilterField.setFont(filterFieldFont);
        toolNameFilterField.setBorder(BorderFactory.createTitledBorder(filterI18n.getText("arsenal.dialog.filter.tool.name")));
        
        // 分类筛选下拉框
        categoryFilterCombo = new JComboBox<>();
        Font comboBoxFont = UIManager.getFont("ComboBox.font");
        if (comboBoxFont == null) comboBoxFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        categoryFilterCombo.setFont(comboBoxFont);
        categoryFilterCombo.addItem(filterI18n.getText("arsenal.dialog.filter.category.all"));
        
        // 清除筛选按钮
        clearFilterButton = new JButton(filterI18n.getText("arsenal.dialog.button.clear.filter"));
        Font clearButtonFont = UIManager.getFont("Button.font");
        if (clearButtonFont == null) clearButtonFont = new Font(Font.SANS_SERIF, Font.PLAIN, 11);
        clearFilterButton.setFont(clearButtonFont.deriveFont(11f));
        clearFilterButton.setPreferredSize(new Dimension(80, 25));
    }
    
    /**
     * 布局组件
     */
    private void layoutComponents() {
        setLayout(new BorderLayout());
        
        // 顶部：筛选面板
        JPanel filterPanel = createFilterPanel();
        add(filterPanel, BorderLayout.NORTH);
        
        // 中部：工具表格
        JScrollPane tableScrollPane = new JScrollPane(toolTable);
        tableScrollPane.setPreferredSize(new Dimension(1180, 200));
        I18nManager layoutI18n = I18nManager.getInstance();
        tableScrollPane.setBorder(BorderFactory.createTitledBorder(layoutI18n.getText("arsenal.dialog.border.tool.list")));
        
        // 命令预览选项卡和运行按钮面板
        JPanel middlePanel = new JPanel(new BorderLayout());
        
        // 选项卡面板
        commandTabbedPane.setPreferredSize(new Dimension(1180, 150));
        middlePanel.add(commandTabbedPane, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 5));
        buttonPanel.add(copyCommandButton);
        buttonPanel.add(runButton);
        middlePanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 组合中部面板
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(tableScrollPane, BorderLayout.NORTH);
        centerPanel.add(middlePanel, BorderLayout.CENTER);
        
        // 底部：执行历史
        resultScrollPane.setPreferredSize(new Dimension(1180, 180));
        
        // 添加到主面板
        add(centerPanel, BorderLayout.CENTER);
        add(resultScrollPane, BorderLayout.SOUTH);
    }
    
    /**
     * 创建筛选面板
     * @return 筛选面板
     */
    private JPanel createFilterPanel() {
        JPanel filterPanel = new JPanel(new GridBagLayout());
        I18nManager panelI18n = I18nManager.getInstance();
        filterPanel.setBorder(BorderFactory.createTitledBorder(panelI18n.getText("arsenal.dialog.border.filter.conditions")));
        filterPanel.setPreferredSize(new Dimension(1180, 80));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 工具名称标签和输入框
        gbc.gridx = 0; gbc.gridy = 0;
        filterPanel.add(new JLabel(panelI18n.getText("arsenal.dialog.filter.label.tool.name")), gbc);
        
        gbc.gridx = 1; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.4;
        filterPanel.add(toolNameFilterField, gbc);
        
        // 分类标签和下拉框
        gbc.gridx = 2; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        filterPanel.add(new JLabel(panelI18n.getText("arsenal.dialog.filter.label.category")), gbc);
        
        gbc.gridx = 3; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.3;
        filterPanel.add(categoryFilterCombo, gbc);
        
        // 清除筛选按钮
        gbc.gridx = 4; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        filterPanel.add(clearFilterButton, gbc);
        
        // 占位符，推送其他组件到左侧
        gbc.gridx = 5; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        filterPanel.add(Box.createHorizontalGlue(), gbc);
        
        return filterPanel;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 表格选择事件
        toolTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = toolTable.getSelectedRow();
                if (selectedRow >= 0) {
                    // 获取实际的工具索引（考虑筛选和排序）
                    int modelRow = toolTable.convertRowIndexToModel(selectedRow);
                    if (modelRow >= 0 && modelRow < filteredToolCommands.size()) {
                        selectedToolCommand = filteredToolCommands.get(modelRow);
                        updateCommandPreview();
                        runButton.setEnabled(true);
                        copyCommandButton.setEnabled(true);
                    } else {
                        selectedToolCommand = null;
                        clearCommandAreas();
                        runButton.setEnabled(false);
                        copyCommandButton.setEnabled(false);
                    }
                } else {
                    selectedToolCommand = null;
                    clearCommandAreas();
                    runButton.setEnabled(false);
                    copyCommandButton.setEnabled(false);
                }
            }
        });
        
        // 运行按钮点击事件
        runButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                executeSelectedCommand();
            }
        });
        
        // 复制命令按钮点击事件（替换原来的刷新变量按钮事件）
        copyCommandButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                copyRenderedCommand();
            }
        });
        
        // 工具名称筛选事件
        toolNameFilterField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) { applyFilters(); }
            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) { applyFilters(); }
            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) { applyFilters(); }
        });
        
        // 分类筛选事件
        categoryFilterCombo.addActionListener(e -> applyFilters());
        
        // 清除筛选按钮事件
        clearFilterButton.addActionListener(e -> clearFilters());
        
        // 选项卡切换事件（可选，用于同步编辑）
        commandTabbedPane.addChangeListener(e -> {
            syncCommandBetweenTabs();
        });
        
        // 原始命令文本变更事件 - 实时同步到渲染命令
        originalCommandArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) { 
                syncOriginalToRendered(); 
            }
            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) { 
                syncOriginalToRendered(); 
            }
            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) { 
                syncOriginalToRendered(); 
            }
        });
    }
    
    /**
     * 创建支持中文的等宽字体
     * @return 字体对象
     */
    private Font createMonospaceFont() {
        // 尝试创建支持中文的等宽字体，优先级：Consolas > 系统字体 > 默认等宽字体
        Font systemFont = UIManager.getFont("TextArea.font");
        Font[] preferredFonts = {
            new Font("Consolas", Font.PLAIN, 11),
            new Font("Microsoft YaHei", Font.PLAIN, 11),
            systemFont != null ? systemFont.deriveFont(11f) : new Font(Font.SANS_SERIF, Font.PLAIN, 11),
            new Font(Font.MONOSPACED, Font.PLAIN, 11)
        };
        
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] availableFonts = ge.getAvailableFontFamilyNames();
        
        for (Font font : preferredFonts) {
            for (String availableFont : availableFonts) {
                if (availableFont.equals(font.getFontName())) {
                    return font;
                }
            }
        }
        
        // 如果都不可用，返回默认字体
        return new Font(Font.MONOSPACED, Font.PLAIN, 11);
    }
    
    /**
     * 同步原始命令到渲染命令选项卡
     */
    private void syncOriginalToRendered() {
        if (httpRequest != null) {
            SwingUtilities.invokeLater(() -> {
                try {
                    String originalCommand = originalCommandArea.getText();
                    String renderedCommand = performVariableReplacement(originalCommand);
                    
                    // 暂时禁用文档监听器防止循环触发
                    int caretPosition = renderedCommandArea.getCaretPosition();
                    renderedCommandArea.setText(renderedCommand);
                    
                    // 保持光标位置
                    try {
                        renderedCommandArea.setCaretPosition(Math.min(caretPosition, renderedCommand.length()));
                    } catch (Exception e) {
                        renderedCommandArea.setCaretPosition(0);
                    }
                } catch (Exception e) {
                    // 静默处理同步错误
                }
            });
        }
    }
    
    /**
     * 在选项卡之间同步命令
     */
    private void syncCommandBetweenTabs() {
        // 当用户切换到渲染命令选项卡时，确保内容是最新的
        int selectedTab = commandTabbedPane.getSelectedIndex();
        if (selectedTab == 1 && httpRequest != null) { // 渲染命令选项卡
            syncOriginalToRendered();
        }
    }
    
    /**
     * 执行变量替换（从原始命令文本进行替换）
     * 使用新的DSL表达式系统
     * @param command 原始命令文本
     * @return 替换后的命令
     */
    private String performVariableReplacement(String command) {
        try {
            if (command == null || command.isEmpty() || httpRequest == null) {
                return command;
            }
            
            // 使用DSL变量替换器（支持函数调用和链式访问）
            if (allSelectedRequests != null && allSelectedRequests.size() > 1) {
                // 批量请求模式
                return dslReplacer.replaceWithList(command, allSelectedRequests, null);
            } else {
                // 单个请求模式
                return dslReplacer.replace(command, httpRequest, httpResponse);
            }
            
        } catch (Exception e) {
            // 如果替换失败，返回原始命令
            return command;
        }
    }
    
    /**
     * 清空命令文本区域
     */
    private void clearCommandAreas() {
        originalCommandArea.setText("");
        renderedCommandArea.setText("");
        variablesPreviewArea.setText("");
    }
    
    /**
     * 更新变量预览
     */
    private void updateVariablesPreview() {
        if (httpRequest == null) {
            I18nManager variableI18n = I18nManager.getInstance();
            variablesPreviewArea.setText(variableI18n.getText("arsenal.dialog.variables.no.request"));
            return;
        }
        
        try {
            // 创建一个简单的变量预览
            Map<String, String> requestVariables = new HashMap<>();
            requestVariables.put("http.request.url", httpRequest.url());
            requestVariables.put("http.request.method", httpRequest.method());
            requestVariables.put("http.request.host", httpRequest.httpService().host());
            requestVariables.put("http.request.port", String.valueOf(httpRequest.httpService().port()));
            requestVariables.put("http.request.path", httpRequest.path());
            requestVariables.put("http.request.protocol", httpRequest.httpService().secure() ? "https" : "http");
            requestVariables.put("http.request.body", httpRequest.bodyToString());
            
            Map<String, String> responseVariables = new HashMap<>();
            if (httpResponse != null) {
                responseVariables.put("http.response.status", String.valueOf(httpResponse.statusCode()));
                responseVariables.put("http.response.body", httpResponse.bodyToString());
            }
            
            // 生成变量预览文本
            StringBuilder preview = new StringBuilder();
            preview.append("# HTTP请求变量预览\n");
            preview.append("# 用法: 在命令中使用 %变量名% 进行替换\n\n");
            
            // 按分类显示变量
            I18nManager variableI18n = I18nManager.getInstance();
            addVariablesByCategory(preview, variableI18n.getText("variables.category.basic"), requestVariables, 
                new String[]{"http.request.url", "http.request.method", "http.request.host", 
                           "http.request.port", "http.request.path", "http.request.protocol"});
            
            addVariablesByCategory(preview, variableI18n.getText("variables.category.headers"), requestVariables, 
                new String[]{"http.request.headers.user-agent", "http.request.headers.cookie", 
                           "http.request.headers.referer", "http.request.headers.authorization"});
            
            addVariablesByCategory(preview, variableI18n.getText("variables.category.body"), requestVariables,
                new String[]{"http.request.body", "body.type", "body.json.field.count"});
            
            addVariablesByCategory(preview, variableI18n.getText("variables.category.file"), requestVariables,
                new String[]{"file.name", "file.extension", "path.directory"});
            
            addVariablesByCategory(preview, variableI18n.getText("variables.category.auth"), requestVariables,
                new String[]{"auth.type", "auth.username", "auth.password", "auth.token"});
            
            // 响应变量
            if (!responseVariables.isEmpty()) {
                preview.append("\n## HTTP响应变量\n");
                addVariablesByCategory(preview, variableI18n.getText("variables.category.response"), responseVariables,
                    new String[]{"http.response.status", "http.response.headers.content-type", 
                               "response.format", "response.html.title"});
            }
            
            // 显示所有可用变量
            preview.append("\n## 所有可用变量 (").append(requestVariables.size() + responseVariables.size()).append(" 个)\n");
            Map<String, String> allVariables = new HashMap<>();
            allVariables.putAll(requestVariables);
            allVariables.putAll(responseVariables);
            
            allVariables.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> {
                    String value = entry.getValue();
                    if (value.length() > 50) {
                        value = value.substring(0, 50) + "...";
                    }
                    preview.append(String.format("%%%-40s%% = %s\n", entry.getKey(), value));
                });
            
            variablesPreviewArea.setText(preview.toString());
            variablesPreviewArea.setCaretPosition(0);
            
        } catch (Exception e) {
            I18nManager parseErrorI18n = I18nManager.getInstance();
            String errorMsg = parseErrorI18n.getText("arsenal.dialog.error.variable.parse", e.getMessage());
            variablesPreviewArea.setText("# 错误\n" + errorMsg);
        }
    }
    
    /**
     * 添加指定分类的变量到预览
     * @param preview 预览文本构建器
     * @param category 分类名称
     * @param variables 变量映射
     * @param keys 要显示的变量键
     */
    private void addVariablesByCategory(StringBuilder preview, String category, 
                                      Map<String, String> variables, String[] keys) {
        preview.append("\n## ").append(category).append("\n");
        for (String key : keys) {
            String value = variables.get(key);
            if (value != null && !value.isEmpty()) {
                if (value.length() > 50) {
                    value = value.substring(0, 50) + "...";
                }
                preview.append(String.format("%%%-40s%% = %s\n", key, value));
            }
        }
    }
    
    /**
     * 应用筛选条件
     */
    private void applyFilters() {
        String toolNameFilter = toolNameFilterField.getText().trim().toLowerCase();
        String categoryFilter = (String) categoryFilterCombo.getSelectedItem();
        
        filteredToolCommands.clear();
        
        for (HttpToolCommand toolCommand : allToolCommands) {
            boolean matchesName = true;
            boolean matchesCategory = true;
            
            // 工具名称筛选
            if (!toolNameFilter.isEmpty()) {
                String toolName = toolCommand.getToolName() != null ? toolCommand.getToolName().toLowerCase() : "";
                matchesName = toolName.contains(toolNameFilter);
            }
            
            // 分类筛选
                                    I18nManager applyI18n = I18nManager.getInstance();
                        if (categoryFilter != null && !categoryFilter.equals(applyI18n.getText("arsenal.dialog.filter.category.all"))) {
                String toolCategory = toolCommand.getCategory();
                matchesCategory = categoryFilter.equals(toolCategory);
            }
            
            if (matchesName && matchesCategory) {
                filteredToolCommands.add(toolCommand);
            }
        }
        
        loadToolData();
    }
    
    /**
     * 清除筛选条件
     */
    private void clearFilters() {
        toolNameFilterField.setText("");
        categoryFilterCombo.setSelectedIndex(0);
        filteredToolCommands.clear();
        filteredToolCommands.addAll(allToolCommands);
        loadToolData();
    }
    
    /**
     * 提取所有分类
     * @return 分类集合
     */
    private Set<String> extractAllCategories() {
        Set<String> categories = new HashSet<>();
        
        try {
            Config config = ConfigManager.getInstance().getConfig();
            if (config.getHttpTool() != null) {
                for (Config.HttpToolCategory category : config.getHttpTool()) {
                    if (category.getType() != null) {
                        categories.add(category.getType());
                    }
                }
            }
        } catch (Exception e) {
        }
        
        return categories;
    }
    
    /**
     * 加载所有工具命令数据
     * @return 工具命令列表
     */
    private List<HttpToolCommand> loadAllToolCommands() {
        try {
            List<HttpToolCommand> toolCommands = ToolController.getInstance().getAllToolCommands();
            
            // 初始化分类下拉框
            SwingUtilities.invokeLater(() -> {
                categoryFilterCombo.removeAllItems();
                I18nManager loadI18n = I18nManager.getInstance();
                categoryFilterCombo.addItem(loadI18n.getText("arsenal.dialog.filter.category.all"));
                
                Set<String> categories = extractAllCategories();
                for (String category : categories.stream().sorted().collect(Collectors.toList())) {
                    categoryFilterCombo.addItem(category);
                }
            });
            
            return toolCommands;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    /**
     * 加载工具数据到表格
     */
    private void loadToolData() {
        tableModel.setRowCount(0); // 清空表格
        
        I18nManager loadDataI18n = I18nManager.getInstance();
        for (HttpToolCommand toolCommand : filteredToolCommands) {
            String toolName = toolCommand.getDisplayName() != null ? toolCommand.getDisplayName() : 
                loadDataI18n.getText("arsenal.dialog.unknown.tool");
            String command = toolCommand.getCommand() != null ? toolCommand.getCommand() : "";
            String note = toolCommand.getNote() != null ? toolCommand.getNote() : "";
            String workDir = toolCommand.getWorkDir() != null ? toolCommand.getWorkDir() : "";
            String category = toolCommand.getCategory() != null ? toolCommand.getCategory() : 
                loadDataI18n.getText("arsenal.dialog.uncategorized");
            
            // 截断过长的命令显示
            String displayCommand = command.length() > 40 ? 
                command.substring(0, 40) + "..." : command;
            
            // 截断过长的备注显示
            String displayNote = note.length() > 20 ? 
                note.substring(0, 20) + "..." : note;
                
            // 截断过长的工作目录显示
            String displayWorkDir = workDir.length() > 15 ? 
                "..." + workDir.substring(workDir.length() - 15) : workDir;
            
            tableModel.addRow(new Object[]{toolName, displayCommand, displayNote, displayWorkDir, category});
        }
        
        // 自动调整列宽和重绘表格
        toolTable.revalidate();
        toolTable.repaint();
        
        // 更新筛选结果统计
        updateFilterStatus();
    }
    
    /**
     * 更新筛选状态显示
     */
    private void updateFilterStatus() {
        I18nManager statusI18n = I18nManager.getInstance();
        String title = statusI18n.getText("arsenal.dialog.title.pattern",
                String.valueOf(filteredToolCommands.size()),
                String.valueOf(allToolCommands.size()));
        setTitle(title);
    }
    

    
    /**
     * 更新命令预览
     */
    private void updateCommandPreview() {
        if (selectedToolCommand != null) {
            try {
                updateOriginalCommandDisplay();
                updateRenderedCommandDisplay();
                updateVariablesPreview();
        } catch (Exception e) {
                handleCommandPreviewError(e);
        }
        }
    }
    
    /**
     * 更新原始命令显示
     */
    private void updateOriginalCommandDisplay() {
                String originalCommand = selectedToolCommand.getCommand() != null ? selectedToolCommand.getCommand() : "";
                originalCommandArea.setText(originalCommand);
                originalCommandArea.setCaretPosition(0);
    }
                
    /**
     * 更新渲染命令显示
     */
    private void updateRenderedCommandDisplay() {
                if (httpRequest != null) {
                    String renderedCommand = generateRenderedCommand(selectedToolCommand, httpRequest);
                    renderedCommandArea.setText(renderedCommand);
                    renderedCommandArea.setCaretPosition(0);
                } else {
                    I18nManager renderI18n = I18nManager.getInstance();
                    renderedCommandArea.setText(renderI18n.getText("arsenal.dialog.no.request.render"));
        }
    }
    
    /**
     * 处理命令预览错误
     * @param e 异常对象
     */
    private void handleCommandPreviewError(Exception e) {
        I18nManager errorI18n = I18nManager.getInstance();
        String errorMessage = errorI18n.getText("command.preview.update.failed") + ": " + e.getMessage();
                originalCommandArea.setText(errorI18n.getText("command.load.failed") + ": " + e.getMessage());
                renderedCommandArea.setText(errorI18n.getText("command.render.failed") + ": " + e.getMessage());
        
    }
    
    /**
     * 生成渲染后的命令
     * 使用新的DSL表达式系统
     * @param toolCommand HTTP工具命令
     * @param request HTTP请求
     * @return 渲染后的命令字符串（纯命令，不包含注释）
     */
    private String generateRenderedCommand(HttpToolCommand toolCommand, HttpRequest request) {
        try {
            String command = toolCommand.getCommand();
            if (command == null || command.isEmpty()) {
                return "";
            }
            
            if (request == null) {
                return command; // 返回原始命令，不添加警告注释
            }
            
            // 使用DSL变量替换器（支持函数调用和链式访问）
            if (allSelectedRequests != null && allSelectedRequests.size() > 1) {
                // 批量请求模式
                return dslReplacer.replaceWithList(command, allSelectedRequests, null);
            } else {
                // 单个请求模式
                return dslReplacer.replace(command, request, httpResponse);
            }
            
        } catch (Exception e) {
            // 记录错误到日志，但返回原始命令
            return toolCommand.getCommand();
        }
    }
    
    

    
    /**
     * 执行选中的命令
     */
    private void executeSelectedCommand() {
        CommandExecutionContext context = prepareCommandExecution();
        if (context == null) {
            return; // 准备失败，已经显示了错误信息
        }
        
        try {
            prepareExecutionUI(context);
            executeCommandInternal(context);
            restoreExecutionUI();
        } catch (Exception e) {
            handleExecutionError(context, e);
        }
    }
    
    /**
     * 准备命令执行上下文
     * @return 命令执行上下文，失败时返回null
     */
    private CommandExecutionContext prepareCommandExecution() {
        int selectedTab = commandTabbedPane.getSelectedIndex();
        I18nManager execI18n = I18nManager.getInstance();
        
        CommandExecutionContext context = new CommandExecutionContext();
        context.selectedTab = selectedTab;
        context.i18n = execI18n;
        
        if (selectedTab == 0) { // 原始命令选项卡
            context.command = originalCommandArea.getText();
            context.commandType = execI18n.getText("arsenal.dialog.execution.original.command");
        } else if (selectedTab == 1) { // 渲染命令选项卡
            context.command = renderedCommandArea.getText();
            context.commandType = execI18n.getText("arsenal.dialog.execution.rendered.command");
        } else {
            JOptionPane.showMessageDialog(this, execI18n.getText("arsenal.dialog.message.select.tab"), 
                execI18n.getText("dialog.title.warning"), JOptionPane.WARNING_MESSAGE);
            return null;
        }
        
        if (context.command == null || context.command.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, execI18n.getText("arsenal.dialog.message.command.empty"), 
                execI18n.getText("dialog.title.error"), JOptionPane.ERROR_MESSAGE);
            return null;
        }
        
        context.toolName = selectedToolCommand != null ? selectedToolCommand.getToolName() : 
            execI18n.getText("arsenal.dialog.manual.command");
        context.toolWorkDir = selectedToolCommand != null ? selectedToolCommand.getWorkDir() : null;
        
        return context;
    }
    
    /**
     * 准备执行UI状态
     * @param context 命令执行上下文
     */
    private void prepareExecutionUI(CommandExecutionContext context) {
        runButton.setEnabled(false);
        runButton.setText(context.i18n.getText("arsenal.dialog.button.running"));
        addExecutionLogEntry(context.i18n.getText("arsenal.dialog.execution.start"), 
            context.toolName, context.commandType, context.command.trim());
    }
    
    /**
     * 执行命令内部逻辑
     * @param context 命令执行上下文
     */
    private void executeCommandInternal(CommandExecutionContext context) throws Exception {
        // 处理命令变量替换
        String finalCommand = processFinalCommand(context);
        
        // 记录最终执行的命令
        addExecutionLogEntry(context.i18n.getText("arsenal.dialog.execution.actual"), context.toolName, 
            context.i18n.getText("arsenal.dialog.execution.system.command"), finalCommand);
        
        // 记录工作目录信息
        logWorkingDirectory(context);
        
        // 使用脚本方式执行命令
        executeCommandViaScript(finalCommand, context.toolName, context.toolWorkDir);
    }
    
    /**
     * 处理最终执行的命令
     * @param context 命令执行上下文
     * @return 处理后的命令
     */
    private String processFinalCommand(CommandExecutionContext context) {
        String finalCommand = context.command.trim();
        
        // 如果是原始命令选项卡且有HTTP请求，需要重新进行变量替换
        if (context.selectedTab == 0 && httpRequest != null) {
            finalCommand = performVariableReplacement(context.command.trim());
        }
        
        return finalCommand;
    }
    
    /**
     * 记录工作目录信息
     * @param context 命令执行上下文
     */
    private void logWorkingDirectory(CommandExecutionContext context) {
        if (context.toolWorkDir != null && !context.toolWorkDir.trim().isEmpty()) {
            addExecutionLogEntry(context.i18n.getText("arsenal.dialog.execution.workdir"), context.toolName, 
                context.i18n.getText("arsenal.dialog.execution.tool.workdir"), context.toolWorkDir);
        }
    }
    
    /**
     * 恢复执行UI状态
     */
    private void restoreExecutionUI() {
            SwingUtilities.invokeLater(() -> {
            I18nManager i18n = I18nManager.getInstance();
                runButton.setEnabled(true);
            runButton.setText(i18n.getText("arsenal.dialog.button.run"));
        });
    }
    
    /**
     * 处理执行错误
     * @param context 命令执行上下文
     * @param e 异常对象
     */
    private void handleExecutionError(CommandExecutionContext context, Exception e) {
        addExecutionLogEntry(context.i18n.getText("arsenal.dialog.execution.script.exception"), context.toolName, 
            context.i18n.getText("arsenal.dialog.execution.error"), e.getMessage());
        
            // 恢复按钮状态
            runButton.setEnabled(true);
        runButton.setText(context.i18n.getText("arsenal.dialog.button.run"));
            
            // 显示错误对话框
            JOptionPane.showMessageDialog(this, 
            context.i18n.getText("arsenal.dialog.copy.failed.pattern", e.getMessage()), 
            context.i18n.getText("dialog.title.error"), 
                JOptionPane.ERROR_MESSAGE);
        }
    
    /**
     * 命令执行上下文类
     */
    private static class CommandExecutionContext {
        int selectedTab;
        String command;
        String commandType;
        String toolName;
        String toolWorkDir;
        I18nManager i18n;
    }
    
    /**
     * 通过ToolExecutor执行命令
     * @param command 要执行的命令
     * @param toolName 工具名称
     * @param toolWorkDir 工具配置的工作目录（可为null）
     */
    private void executeCommandViaScript(String command, String toolName, String toolWorkDir) {
        try {
            I18nManager scriptI18n = I18nManager.getInstance();
            addExecutionLogEntry(scriptI18n.getText("arsenal.dialog.execution.start"), toolName, 
                scriptI18n.getText("arsenal.dialog.execution.system.command"), command);
            
            // 记录工作目录信息
            if (toolWorkDir != null && !toolWorkDir.trim().isEmpty()) {
                addExecutionLogEntry(scriptI18n.getText("arsenal.dialog.execution.workdir"), toolName, 
                    scriptI18n.getText("arsenal.dialog.execution.tool.workdir"), toolWorkDir);
            }
            
            // 使用ToolExecutor执行命令
            ToolExecutor.getInstance().executeCommandViaScript(command, toolName, toolWorkDir);
            
            addExecutionLogEntry(scriptI18n.getText("arsenal.dialog.execution.script.started"), toolName, 
                scriptI18n.getText("arsenal.dialog.execution.success"), scriptI18n.getText("arsenal.dialog.script.started.success"));
            
        } catch (Exception e) {
            I18nManager scriptExecI18n = I18nManager.getInstance();
            addExecutionLogEntry(scriptExecI18n.getText("arsenal.dialog.execution.script.exception"), toolName, 
                scriptExecI18n.getText("arsenal.dialog.execution.error"), e.getMessage());
            // 恢复按钮状态
            runButton.setEnabled(true);
            runButton.setText(scriptExecI18n.getText("arsenal.dialog.button.run"));
            
            // 显示错误对话框
            JOptionPane.showMessageDialog(this, 
                scriptExecI18n.getText("arsenal.dialog.copy.failed.pattern", e.getMessage()), 
                scriptExecI18n.getText("dialog.title.error"), 
                JOptionPane.ERROR_MESSAGE);
        }
    }
    
    
    /**
     * 添加执行日志条目
     * @param action 操作类型
     * @param toolName 工具名称
     * @param type 类型
     * @param details 详细信息
     */
    private void addExecutionLogEntry(String action, String toolName, String type, String details) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = formatter.format(new java.util.Date());
        
        I18nManager logI18n = I18nManager.getInstance();
        StringBuilder logEntry = new StringBuilder();
        logEntry.append("[").append(timestamp).append("] ");
        logEntry.append(action).append(" - ");
        logEntry.append(logI18n.getText("arsenal.dialog.execution.tool")).append(": ").append(toolName).append(" | ");
        logEntry.append(logI18n.getText("arsenal.dialog.execution.type")).append(": ").append(type).append("\n");
        
        // 如果details太长，进行截断显示
        String displayDetails = details;
        if (details.length() > 200) {
            displayDetails = details.substring(0, 200) + "...";
        }
        logEntry.append(logI18n.getText("arsenal.dialog.execution.details")).append(": ").append(displayDetails).append("\n");
        logEntry.append(createSeparator(50)).append("\n");
        
        commandResultArea.append(logEntry.toString());
        commandResultArea.setCaretPosition(commandResultArea.getDocument().getLength());
    }
    
    /**
     * 创建分隔符字符串
     * @param length 分隔符长度
     * @return 分隔符字符串
     */
    private String createSeparator(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append("=");
        }
        return sb.toString();
    }
    


    /**
     * 复制渲染后的命令到剪贴板
     */
    private void copyRenderedCommand() {
        I18nManager copyI18n = I18nManager.getInstance();
        if (selectedToolCommand == null) {
            JOptionPane.showMessageDialog(this, copyI18n.getText("arsenal.dialog.message.select.tool"), 
                copyI18n.getText("dialog.title.warning"), JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        try {
            // 总是复制渲染后的命令，不依赖当前选中的选项卡
            String commandToCopy = renderedCommandArea.getText();
            String commandType = copyI18n.getText("arsenal.dialog.copy.type.rendered");
            
            if (commandToCopy == null || commandToCopy.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, copyI18n.getText("arsenal.dialog.message.rendered.empty"), 
                    copyI18n.getText("dialog.title.warning"), JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 复制到系统剪贴板
            StringSelection stringSelection = new StringSelection(commandToCopy.trim());
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
            
            // 显示成功提示
            String toolName = selectedToolCommand.getToolName();
            String message = copyI18n.getText("arsenal.dialog.copy.success.pattern", 
                commandType, toolName, String.valueOf(commandToCopy.trim().length()));
            JOptionPane.showMessageDialog(this, message, copyI18n.getText("arsenal.dialog.copy.success.title"), 
                JOptionPane.INFORMATION_MESSAGE);
            
            // 记录到执行历史
            addExecutionLogEntry(copyI18n.getText("arsenal.dialog.execution.tool"), toolName, commandType, 
                copyI18n.getText("arsenal.dialog.copied.clipboard", String.valueOf(commandToCopy.trim().length())));
            
            // 记录到Burp日志
            
        } catch (Exception ex) {
            String errorMsg = copyI18n.getText("arsenal.dialog.copy.failed.pattern", ex.getMessage());
            JOptionPane.showMessageDialog(this, errorMsg, copyI18n.getText("arsenal.dialog.copy.failed.title"), 
                JOptionPane.ERROR_MESSAGE);
            
        }
    }
    
    
    
    /**
     * 语言变更监听器实现
     */
    @Override
    public void onLanguageChanged(I18nManager.SupportedLanguage newLanguage) {
        SwingUtilities.invokeLater(() -> {
            updateUITexts();
            revalidate();
            repaint();
        });
    }
    
    /**
     * 更新UI文本
     */
    private void updateUITexts() {
        I18nManager i18n = I18nManager.getInstance();
        
        // 更新对话框标题
        setTitle(i18n.getText("dialog.arsenal.title"));
        
        // 更新按钮文本
        updateButtonTexts(i18n);
        
        // 更新表格列标题
        updateTableHeaders(i18n);
        
        // 更新标签文本
        updateLabelTexts(i18n);
    }
    
    /**
     * 更新按钮文本
     */
    private void updateButtonTexts(I18nManager i18n) {
        try {
            if (runButton != null) {
                runButton.setText(i18n.getText("arsenal.dialog.button.run"));
            }
            if (copyCommandButton != null) {
                copyCommandButton.setText(i18n.getText("arsenal.dialog.button.copy.command"));
            }
            if (clearFilterButton != null) {
                clearFilterButton.setText(i18n.getText("arsenal.dialog.button.clear.filter"));
            }
        } catch (Exception e) {
            // 忽略更新错误
        }
    }
    
    /**
     * 更新表格列标题
     */
    private void updateTableHeaders(I18nManager i18n) {
        if (tableModel != null) {
            try {
                // 更新表格列名
                tableModel.setColumnIdentifiers(new String[]{
                    i18n.getText("arsenal.dialog.table.column.tool.name"),
                    i18n.getText("arsenal.dialog.table.column.command"),
                    i18n.getText("arsenal.dialog.table.column.note"),
                    i18n.getText("arsenal.dialog.table.column.work.dir"),
                    i18n.getText("arsenal.dialog.table.column.category")
                });
            } catch (Exception e) {
                // 忽略更新错误
            }
        }
    }
    
    /**
     * 更新标签文本
     */
    private void updateLabelTexts(I18nManager i18n) {
        try {
            // 更新选项卡标题
            if (commandTabbedPane != null) {
                commandTabbedPane.setTitleAt(0, i18n.getText("arsenal.dialog.tab.original.command"));
                commandTabbedPane.setTitleAt(1, i18n.getText("arsenal.dialog.tab.rendered.command"));
                commandTabbedPane.setTitleAt(2, i18n.getText("arsenal.dialog.tab.variables.preview"));
                
                // 更新选项卡提示
                commandTabbedPane.setToolTipTextAt(0, i18n.getText("arsenal.dialog.tab.tooltip.original"));
                commandTabbedPane.setToolTipTextAt(1, i18n.getText("arsenal.dialog.tab.tooltip.rendered"));
                commandTabbedPane.setToolTipTextAt(2, i18n.getText("arsenal.dialog.tab.tooltip.variables"));
            }
            
            // 更新边框标题
            if (commandResultArea != null) {
                commandResultArea.setBorder(BorderFactory.createTitledBorder(i18n.getText("arsenal.dialog.execution.history")));
            }
            
            // 更新分类下拉框
            if (categoryFilterCombo != null && categoryFilterCombo.getItemCount() > 0) {
                String selectedItem = (String) categoryFilterCombo.getSelectedItem();
                String allCategoriesText = i18n.getText("arsenal.dialog.filter.category.all");
                categoryFilterCombo.removeItemAt(0);
                categoryFilterCombo.insertItemAt(allCategoriesText, 0);
                if (selectedItem != null && selectedItem.equals(allCategoriesText)) {
                    categoryFilterCombo.setSelectedIndex(0);
                }
            }
            
        } catch (Exception e) {
            // 忽略更新错误
        }
    }
} 